package zheezes.protocol.impl.gbw.format;

import java.util.Calendar;

import zheezes.util.ByteUtil;
import zheezes.util.IntUtil;


public class DataForm01 extends DataForm {
	public static final int SIZE = 6;
	
	private Calendar cal = Calendar.getInstance();
	
	public DataForm01() {
		cal.set(Calendar.MILLISECOND, 0);
	}

	@Override
	public int sizeof() {
		return SIZE;
	}

	@Override
	public int getBytes(byte[] buf, int offset) {
		int idx = offset;
		buf[idx++] = ByteUtil.binToBcd((byte) cal.get(Calendar.SECOND));
		buf[idx++] = ByteUtil.binToBcd((byte) cal.get(Calendar.MINUTE));
		buf[idx++] = ByteUtil.binToBcd((byte) cal.get(Calendar.HOUR_OF_DAY));
		buf[idx++] = ByteUtil.binToBcd((byte) cal.get(Calendar.DATE));
		byte week = (byte) cal.get(Calendar.DAY_OF_WEEK);
		if (week == Calendar.SUNDAY) {
			week = 7;
		} else {
			week--;
		}
		byte month = (byte) (cal.get(Calendar.MONDAY) + 1);
		buf[idx++] = (byte) (((week << 5) & 0xE0) | (ByteUtil.binToBcd(month) & 0x1F));
		buf[idx++] = ByteUtil.binToBcd((byte) (cal.get(Calendar.YEAR) % 100));

		return idx - offset;
	}

	@Override
	public int setBytes(byte[] buf, int offset) {
		int idx = offset;
		cal.set(Calendar.SECOND, ByteUtil.bcdToBin(buf[idx++]));
		cal.set(Calendar.MINUTE, ByteUtil.bcdToBin(buf[idx++]));
		cal.set(Calendar.HOUR_OF_DAY, ByteUtil.bcdToBin(buf[idx++]));
		cal.set(Calendar.DATE, ByteUtil.bcdToBin(buf[idx++]));
		cal.set(Calendar.MONTH, ByteUtil.bcdToBin((byte) ((buf[idx++] - 1) & 0x1F)));
		cal.set(Calendar.YEAR, IntUtil.cutLow(cal.get(Calendar.YEAR), 2) + ByteUtil.bcdToBin(buf[idx++]));

		return idx - offset;
	}

	public Calendar getCal() {
		return (Calendar) cal.clone();
	}

	public void setCal(Calendar cal) {
		this.cal = (Calendar) cal.clone();
	}
}
